<?php
$db = mssql_connect('vcnsql89\i89','posiverse','<redacted>');
mssql_select_db('posiverse');
$userid = 0;

if (isset($_COOKIE['skeleton'])) {
	
	checkCookie($_COOKIE['skeleton']);
	
} else {

	newCookie();	
	
}




// Functions below this line.


function newCookie() {

	// We make a string cookie, and only store the hash in the database.
	// All cookie comparisons are done with the hash.
	$a = time();
	for ($x = 0; $x < 50; $x++) { 
		$a .= chr(rand(97,122));
	}
	
	$ck = md5($a);
	
	$query = "insert into Skel_cky (Cookie, userID, CreatedOn, UpdatedOn) values ('$ck',0,GETDATE(),GETDATE())";
	mssql_query($query);
	
	setcookie("skeleton",$a,time()+1800,"/",".posiverse.com");
	
}

function checkCookie($cookie) {

	global $userid;

	$ck = md5($cookie);
	$query = "select * from Skel_cky where Cookie = '$ck' and DATEADD(hour,1,UpdatedOn) > GETDATE()";
	$res = mssql_query($query);
	if ($res && mssql_num_rows($res) == 1) {
		$rec = mssql_fetch_assoc($res);
		$userid = $rec['userID'];
		$query = "update Skel_cky set UpdatedOn = GETDATE() where Cookie = '$ck'";
		mssql_query($query);
		setcookie("skeleton",$cookie,time()+1800,"/",".posiverse.com");
	} else {
		newCookie();
	}
	
}

function checkPassword($login,$pass) {

	global $userid;

	$login = md5($login);
	$pass = md5($pass);
	
	$query = "select * from Skel_users where User_MD5 = '$login' and Password_MD5 = '$pass'";
	$res = mssql_query($query);
	if ($res && mssql_num_rows($res) == 1) {
		$rec = mssql_fetch_assoc($res);
		$userid = $rec['ID'];
		if (isset($_COOKIE['skeleton'])) {
			$query = "update Skel_cky set userID = " . $rec['ID'] . " where Cookie = '" . md5($_COOKIE['skeleton']) . "'";
			mssql_query($query);
		}
		return "OK";
	} else {
		return "ERROR";
	}
	
}

?>
